package net.trade.trade.service;

import java.util.HashMap;
import java.util.List;

import net.core.base.dao.CommonDAO;
import net.core.common.DateFormater;
import net.core.common.StrUtils;
import net.system.sys.service.ICommService;
import net.trade.trade.dao.FundDAO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alipay.util.AlipayNotify;

@Service
public class FundServiceImpl implements IFundService {
	final Logger logger = LoggerFactory.getLogger(FundServiceImpl.class);
	@Autowired
	private CommonDAO commonDAO;
	
	@Autowired
	private FundDAO fundDAO;
	
	@Autowired
	private ICommService commService;

	@Override
	public String rechargeAdd(HashMap map) {
		String sql = "INSERT INTO `t_fundlog`(`rec_id`, `user_id`, `status`, `amount`, `type`, `rec_time`) VALUES ([value])";

		String value = "";
		String recId = commService.getSeq("fund");
		value += "'" + recId + "'";
		String userId = StrUtils.getNotNullStrValue(map.get("userId"));
		value += ",'" + userId + "'";
		value += ",'Invalid'";
		String amount = StrUtils.getNotNullStrValue(map.get("amount"));
		value += ",'" + amount + "'";
		value += ",'recharge'";
		String time = DateFormater.getNowTime();
		value += ",'" + time + "'";
		sql = sql.replace("[value]", value);
		int i = commonDAO.insertSql(sql);

		return i + "";
	}

	@Override
	public String drawAdd(HashMap map) {
		// 判断活动金额是否够提现
		String sql = "INSERT INTO `t_fundlog`(`rec_id`, `user_id`, `status`, `amount`, `type`, `rec_time`) VALUES ([value])";

		String value = "";
		String recId = commService.getSeq("fund");
		value += "'" + recId + "'";
		String userId = StrUtils.getNotNullStrValue(map.get("userId"));
		value += ",'" + userId + "'";
		value += ",'Invalid'";
		String amount = StrUtils.getNotNullStrValue(map.get("amount"));
		value += ",'" + amount + "'";
		value += ",'draw'";
		String time = DateFormater.getNowTime();
		value += ",'" + time + "'";
		sql = sql.replace("[value]", value);
		int i = commonDAO.insertSql(sql);

		return i + "";
	}

	@Override
	public List<HashMap> selectUserFundflow(HashMap map) {
		String userId = StrUtils.getNotNullStrValue(map.get("userId"));
		String sql = "select `user_id`, `status`, `amount`, `type`, `rec_time`"
				+ ",case when status='Invalid' then '待受理' when status='Effective' then '成功' end statusname"
				+ ", case when type='recharge' then '充值' else '提现' end typename from `t_fundlog` where 1=1  ";
		if(!"admin".equals(userId)){
			// 不是管理员，则依据用户ID来查找
			if(!"".equals(userId)){
				sql += " and `user_id`='"+userId+"' ";
			}
		}
		// TODO 要考虑分页查找
		List<HashMap> list = commonDAO.getDataList(sql);
		return list;
	}

	@Override
	public List userFundList(HashMap<String, String> param) {
		return fundDAO.userFundList(param);
	}

	@Override
	public List userFundCount(HashMap<String, String> param) {
		// TODO Auto-generated method stub
		return fundDAO.userFundCount(param);
	}

	@Override
	public String fundReturn(HashMap map) {
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号

		String out_trade_no = StrUtils.getNotNullStrValue(map.get("out_trade_no"));

		//支付宝交易号

		String trade_no = StrUtils.getNotNullStrValue(map.get("trade_no"));

		//交易状态
		String trade_status = StrUtils.getNotNullStrValue(map.get("trade_status"));

		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		
		//计算得出通知验证结果
		boolean verify_result = AlipayNotify.verify(map);
		
		if(verify_result){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码

			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
				String sql ="update s_fundlog set status='Effective',alipay_no='"+trade_no+"' where rec_id='"+out_trade_no+"'";
				commonDAO.updateSql(sql);
			}
			
			//该页面可做页面美工编辑
//			out.println("验证成功<br />");
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

			//////////////////////////////////////////////////////////////////////////////////////////
		}else{
			//该页面可做页面美工编辑
//			out.println("验证失败");
		}
		return null;
	}

	@Override
	public List manageFundList(HashMap<String, String> param) {
		return fundDAO.manageFundList(param);
	}

	@Override
	public List manageFundCount(HashMap<String, String> param) {
		return fundDAO.manageFundCount(param);
	}

	@Override
	public String addUserFund(HashMap map) {
		String result = "";
		// 记录日志
		result=rechargeAdd(map);
		result=updAccount(map);
		return result;
	}

	private String updAccount(HashMap map) {
		String result = "";
		result= fundDAO.updAccount(map);
		return result;
	}
}
